package com.cxs.auth;

import com.cxs.model.Users;
import com.cxs.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Set;

/*
 * @Author:cxs
 * @Date:2021/10/14  16:25
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        if(StringUtils.isEmpty(username)){
            throw new AccountException("用户名不能为空");
        }

        Users user = userService.findUserByUsername(username);

        if(user == null) {
            throw new UnknownAccountException("用户名不存在");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),"userRealm");

        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        Users user = (Users) principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Set<String> roleSet = new HashSet<>();
        roleSet.add("user");
        info.setRoles(roleSet);

        Set<String> premsSet = new HashSet<>();
        roleSet.add("user:select");
        info.setStringPermissions(premsSet);
        return info;
    }
}
